package com.xgsm.springsecurityauthdemo.Filters;

import com.xgsm.springsecurityauthdemo.domain.UserLogin;
import com.xgsm.springsecurityauthdemo.utils.JwtUtil;
import com.xgsm.springsecurityauthdemo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//1、获取token  header的token
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {//获取不到token，即未登录
            //放行即可，交给过滤器处理,让后面的过滤器执行
            filterChain.doFilter(request, response);
            return;
        }
        String UserId;
        //2、解析token
        try {
            Claims claims = JwtUtil.parseJWT(token);
        //3、获取UserId
            UserId = claims.getSubject();

        } catch (Exception e) {
            throw new RuntimeException("token不合法");
        }
        //获取用户信息（用户信息在redis中）
        UserLogin userLogin = redisCache.getCacheObject("login:" + UserId);
        if (Objects.isNull(userLogin)){
            throw new RuntimeException("当前用户未登录");
        }
        //        4、封装Authentication
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(userLogin,null,userLogin.getAuthorities());
//        5、存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行，让后面的过滤器执行
        filterChain.doFilter(request, response);
    }
}
